package xyz.ccola.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;
import java.util.Objects;

/**
 * @ Name: MyBatisUtils
 * @ Author: Cola
 * @ Time: 2023/1/5 14:49
 * @ Description: MyBatisUtils 工具类
 */
public class MyBatisUtils {
    private static SqlSessionFactory sqlSessionFactory = null;

    static {
        try {
            // 通过字符流的方式读取配置并构建 sessionFactory
            Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取 sqlSession
     * @return sqlSession
     */
    public static SqlSession getSession(){
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        return Objects.requireNonNull(sqlSession);
    }
}
